package com.itstu.gulimall.product.web;

import com.itstu.common.utils.R;
import com.itstu.gulimall.product.entity.CategoryEntity;
import com.itstu.gulimall.product.service.CategoryService;
import com.itstu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author shhjiang_001
 * @create 2020-05-25 12:00
 */
//@RestController  这个注解是相当于@ResponseBody ＋ @Controller合在一起的作用，由于类内部有跳转路径的方法，因此不能用。
@Controller
public class indexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redisson;
    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Category();
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }
    // "index/catalog.json"
    @ResponseBody// 将返回结果直接写入HTTP正文中，不会解析为跳转路径（可以越过视图解析器）
    @GetMapping("/index/json/catalog.json")
    public Map<String,List<Catelog2Vo>> getCatelogJson(){
        System.out.println(Thread.currentThread().getId());
        Map<String,List<Catelog2Vo>> catelogJson = categoryService.getCatalogJson();
        return catelogJson;
    }
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        RLock lock = redisson.getLock("my-lock");
        lock.lock();
        try {
            System.out.println("加锁成功,执行事务"+Thread.currentThread().getId());
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }finally {
            lock.unlock();
            System.out.println("解锁成功"+Thread.currentThread().getId());
        }

        return "hello";
    }

    @RequestMapping("list/tree")
    @ResponseBody
    public R listWithTree(){
        List<CategoryEntity> entities = categoryService.listTree();
        return R.ok().put("data",entities);
    }

}
